/**
 * Created with JetBrains WebStorm.
 * User: johnsonc : urbanskia
 * Date: 11/6/2012
 * Time: 8:23 AM
 * To change this template use File | Settings | File Templates.
 */
(function(){
    var selectedRow;
    var selectedCol;

    var textAreaKeyDown = function(event, caller){

        if(event.keyCode == 9 && !event.shiftKey){
            // Data tag of the current text area
            var data = $(caller).data();

            // variables that list the current table position
            var currColNumber = data.td;

            var numColumns = $(caller).parents('tr').children('td').length;

            if( currColNumber >= (numColumns - 1) ){
                // All the rows in the table
                var rows = $(caller).parents('table').find('tr');

                //changed key to index (Cole)
                $.each( rows, function(index, row){
                        var td = $('<td></td>');
                        var textarea = $('<textarea class="editable" data-tr="' + index + '" data-td="' + (currColNumber + 1) + '"></textarea>');
                        textarea.keydown(function(event){
                           textAreaKeyDown(event, this);
                        }).focus(function(event){
                                selectedRow = $(this).data().tr;
                                selectedCol = $(this);
                        })
                        .blur(function(event){
                            selectedRow = $(this);
                            selectedCol = $(this);
                        });
                        var newCell = td.append(textarea);
                        $(row).append(newCell);
                });
            }
        }

        if(event.keyCode == 13 && !event.shiftKey){
            event.preventDefault();
            var data = $(caller).data();
            var currRowNumber = data.tr;
            var currColNumber = data.td;

            var numRows = $(caller).parents('table').find('tr').length;

            if(currRowNumber >= (numRows - 1)){
                var tr = $('<tr></tr>');

                var cols = $(caller).parents('tr').find('td');

                $.each(cols, function(index, col){
                    var td = $('<td></td>');
                    var textarea = $('<textarea class="editable" data-tr="' + (currRowNumber + 1) + '" data-td="' + index + '"></textarea>');
                    textarea.keydown(function(event){
                        textAreaKeyDown(event, this);
                    }).focus(function(event){
                            selectedRow = $(this);
                            selectedCol = $(this);
                     })
                    .blur(function(event){
                        selectedRow = $(this);
                        selectedCol = $(this);
                    });
                    var newCell = td.append(textarea);
                    tr.append(td);
                });

                $('table').append(tr);
            }
            currElement = $('table tr:nth-child(' + ( currRowNumber + 2 ) + ') td:nth-child(' + ( currColNumber + 1 ) + ') textarea');
            $(currElement).focus();
        }

        if(event.keyCode == 13 && event.shiftKey){
            event.preventDefault();
            var data = $(caller).data();
            var currRowNumber = data.tr;
            var currColNumber = data.td;
            if(currRowNumber != 0){
                currElement = $('table tr:nth-child(' + currRowNumber + ') td:nth-child(' + ( currColNumber + 1 ) + ') textarea');
                $(currElement).focus();
            }
        }

        if(event.keyCode == 46 && event.shiftKey){
            deleteColumn();
        }

        if(event.keyCode == 46 && event.ctrlKey){
            deleteRow();
        }
    }

    var saveFile = function(data){
        var csv = '';
         $.each(data.tableObjects, function(key, value){
            var totalLen = $(value).find('tr').length;
            $.each($(value).find('tr'), function(rowKey, value){
                var len = $(value).children().length;
                $.each($(value).children(), function(colKey, value){
                    var item = $(value).children().val();
                    if( colKey == len -1 && rowKey != totalLen -1 ){
                        csv += item + '\r\n';
                    }
                    else if( colKey == len -1 && rowKey == totalLen -1 ){
                        csv += item;
                    }
                    else{
                        csv += item + ',';
                    }
                });
            });
        });
        uriContent = "data:application/octet-stream;filename=filename.txt," + encodeURIComponent(csv);
        window.open(uriContent, "filename=filename.txt");
    }

    var openFile = function(){
        if (window.File && window.FileReader && window.FileList && window.Blob) {
            var data = document.getElementById('open-file-input').files[0]
            if(data){
                // The area in which to append the opened table
                var tableArea = $('#tableArea');

                // The table that is being built
                var openedTable = $('<table class="editable"></table>');
                var reader = new FileReader();
                reader.onload = function(event){
                    var contents = event.target.result;
                    // The comma separated individual rows
                    var tableRows = contents.split('\r\n');
                    $.each(tableRows, function(rowKey, row){
                        // The current row that is being built in the table
                        var tableRow = $('<tr></tr>');
                        var tableCols = row.split(',');
                        $.each(tableCols, function(columnKey, column){
                            // The current column that is being built in the table row
                            var tableColumn = $('<td></td>');
                            var textarea = $('<textarea class="editable" data-tr="' + rowKey + '" data-td="' + columnKey + '">' + column + '</textarea>');

                            textarea.keydown(function(event){
                                textAreaKeyDown(event, this);
                            })
                            .focus(function(event){
                                selectedRow = $(this);
                                selectedCol = $(this);
                            })
                            .blur(function(event){
                                    selectedRow = $(this);
                                    selectedCol = $(this);
                            });
                            tableColumn.append(textarea);
                            tableRow.append(tableColumn);
                        });
                        openedTable.append(tableRow);
                    });
                    tableArea.html(openedTable);
                }
                reader.readAsText(data);
            }
            else{
                alert("Failed to load file");
            }
        } else {
            alert('The File APIs are not fully supported by your browser.');
        }
    }

    var deleteColumn = function(){

        // The current column number of the to be deleted column
        var currCol = $(selectedCol).data().td;

        // The table in which the column exists, in case there are more than one table on the page
        var parentTable = $(selectedCol).parents('table');

        var colDeleted = false;
        // For each row in the table
        $.each($(parentTable).find('tr'), function(key, value){
            // For each td in a row
            $.each($(value).children(), function(key, value){
                // Get the column number of the textarea inside a td tag
                var textAreaCol = $(value).children().data().td;
                // If the textarea is in the to be deleted row, delete the td it is contained inside of
                if(textAreaCol == currCol){
                    $(value).detach();
                    colDeleted = true
                }
            });
        });
        if(colDeleted){
            refreshTableTrTd(parentTable);
        }
    }

    var refreshTableTrTd = function(parentTable){
        $.each($(parentTable).find('tr'), function(rowNumber, value){
            $.each($(value).children(), function(colNumber, value){
                $(value).children().data("tr", rowNumber);
                $(value).children().data("td", colNumber);
                $('textarea').keydown(function(event){
                    textAreaKeyDown(event, this);
                })
            });
        });
    }

    var deleteRow = function(){

        // The current row number of the to be deleted column
        var currRow = $(selectedRow).data().tr;
        var currCol = $(selectedCol).data().td;

        //The table in which the row exists, in case there are more than one table on the page
        var parentTable = $(selectedRow).parents('table');

        var rowDeleted = false;
        $.each($(parentTable).find('tr'), function(key, value){
            var textAreaRow = $(value).find('textarea');
            textAreaRow = $(textAreaRow).data().tr;
             if(textAreaRow == currRow){
                $(value).detach();
                rowDeleted = true;
            }
        });
        if(rowDeleted){
            refreshTableTrTd(parentTable);
        }

    }

    $(document).ready(function(){
        $('#open-file-dialog').dialog({
            title: 'Open File',
            autoOpen: false,
            width: 410,
            height: 150
        })

        $('textarea').keydown(function(event){
            textAreaKeyDown(event, this);
        });

        $('textarea').focus(function(event){
           selectedRow = $(this);
            selectedCol = $(this);
         })
        .blur(function(event){
            selectedRow = $(this);
            selectedCol = $(this);
        });;

        $('#open-file-dialog-button').click(function(){
            $('#open-file-dialog').dialog('open');
        });

        $('#open-file-button').click(function(){
            openFile();
            $('#cancel-file-button').click();
        });

        $('#cancel-file-button').click(function(){
            $('#open-file-dialog').dialog('close');
            $('#open-file-input').val('');
        });

        $('#save-button').click(function(event){
            var tableObjects = $('#tableArea').find('table')

            var saveObject = {
                'fileName' : $('#save-file').val(),
                'tableObjects' : tableObjects
            }
            saveFile(saveObject);
        });

        $('#delete-col-button').click(function(event){
            deleteColumn();
        });

        $('#delete-row-button').click(function(event){
            deleteRow();
        });
    })

})();